home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus 2000 #5 / Amiga Plus CD - 2000 - No. 5.iso / Tools / Dev / lame_src / get_audio.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-01-01  |  30.7 KB  |  1,096 lines

  1. #include "util.h"
  2. #include "get_audio.h"
  3. #include "portableio.h"
  4. #include "gtkanal.h"
  5. #include "timestatus.h"
  6.  
  7. #if (defined LIBSNDFILE || defined LAMESNDFILE)
  8.  
  9. #ifdef _WIN32
  10. /* needed to set stdin to binary on windoze machines */
  11. #include <io.h>
  12. #endif
  13.  
  14. #ifdef __riscos__
  15. #include <kernel.h>
  16. #include <sys/swis.h>
  17. #endif
  18.  
  19.  
  20. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304],int frame_size, int samples_to_read);
  21. int read_samples_mp3(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int num_chan);
  22. int read_samples_ogg(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int num_chan);
  23.  
  24.  
  25. void lame_init_infile(lame_global_flags *gfp)
  26. {
  27.   lame_internal_flags *gfc=gfp->internal_flags;
  28.   /* open the input file */
  29.   gfc->count_samples_carefully=0;
  30.   gfp->musicin=OpenSndFile(gfp);
  31. }
  32. void lame_close_infile(lame_global_flags *gfp)
  33. {
  34.   CloseSndFile(gfp->input_format,gfp->musicin);
  35. }
  36.  
  37.  
  38.  
  39.  
  40. /************************************************************************
  41. *
  42. * lame_readframe()
  43. *
  44. * PURPOSE:  reads a frame of audio data from a file to the buffer,
  45. *   aligns the data for future processing, and separates the
  46. *   left and right channels
  47. *
  48. *
  49. ************************************************************************/
  50. int lame_readframe(lame_global_flags *gfp,short int Buffer[2][1152])
  51. {
  52.   int iread;
  53.   lame_internal_flags *gfc=gfp->internal_flags;
  54.  
  55.  
  56.   /* note: if input is gfp->stereo and output is mono, get_audio()
  57.    * will return  .5*(L+R) in channel 0,  and nothing in channel 1. */
  58.   iread = get_audio(gfp,Buffer,gfc->stereo);
  59.  
  60.   /* check to see if we overestimated/underestimated totalframes */
  61.   if (iread==0)  gfp->totalframes = Min(gfp->totalframes,gfp->frameNum+2);
  62.   if (gfp->frameNum > (gfp->totalframes-1)) gfp->totalframes = gfp->frameNum;
  63.  
  64.   /* normally, frame counter is incremented every time we encode a frame, but: */
  65.   if (gfp->decode_only) ++gfp->frameNum;
  66.   return iread;
  67. }
  68.  
  69.  
  70.  
  71.  
  72.  
  73. /************************************************************************
  74. *
  75. * get_audio()
  76. *
  77. * PURPOSE:  reads a frame of audio data from a file to the buffer,
  78. *   aligns the data for future processing, and separates the
  79. *   left and right channels
  80. *
  81. *
  82. ************************************************************************/
  83. int get_audio(lame_global_flags *gfp,short buffer[2][1152],int stereo)
  84. {
  85.  
  86.   int        j;
  87.   short    insamp[2304];
  88.   int samples_read;
  89.   int framesize,samples_to_read;
  90.   unsigned long remaining;
  91.   lame_internal_flags *gfc=gfp->internal_flags;
  92.   int num_channels = gfp->num_channels;
  93.  
  94.   /* NOTE: LAME can now handle arbritray size input data packets,
  95.    * so there is no reason to read the input data in chuncks of
  96.    * size "gfp->framesize".  EXCEPT:  the LAME graphical frame analyzer 
  97.    * will get out of sync if we read more than framesize worth of data.
  98.    */
  99.   framesize = gfp->framesize;
  100.  
  101.   samples_to_read = framesize;
  102.   if (gfc->count_samples_carefully) {
  103.     /* if this flag has been set, then we are carefull to read
  104.      * exactly num_samples and no more.  This is usefull for .wav and .aiff
  105.      * files which have id3 or other tags at the end.  Note that if you
  106.      * are using LIBSNDFILE, this is not necessary */
  107.     remaining=gfp->num_samples-Min(gfp->num_samples,gfc->num_samples_read);
  108.     if (remaining < (unsigned long)framesize)
  109.       samples_to_read = remaining;
  110.   }
  111.  
  112.  
  113.   if (gfp->input_format==sf_mp3) {
  114.     /* decode an mp3 file for the input */
  115.     samples_read=read_samples_mp3(gfp,gfp->musicin,buffer,num_channels);
  116.   } else if (gfp->input_format==sf_ogg) {
  117.     samples_read=read_samples_ogg(gfp,gfp->musicin,buffer,num_channels);
  118.   }else{
  119.     samples_read = read_samples_pcm(gfp,insamp,num_channels*framesize,num_channels*samples_to_read);
  120.     samples_read /=num_channels;
  121.  
  122.     for(j=0;j<framesize;j++) {
  123.       buffer[0][j] = insamp[num_channels*j];
  124.       if (num_channels==2) buffer[1][j] = insamp[2*j+1];
  125.       else buffer[1][j]=0;
  126.     }
  127.   }
  128.  
  129.   /* dont count things in this case to avoid overflows */
  130.   if (gfp->num_samples!=MAX_U_32_NUM) gfc->num_samples_read += samples_read;
  131.   return(samples_read);
  132.  
  133. }
  134.  
  135.  
  136.   
  137.  
  138.  
  139.  
  140. int read_samples_ogg(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int stereo)
  141. {
  142. #ifdef HAVEVORBIS
  143.   int j,out=0;
  144.   lame_internal_flags *gfc=gfp->internal_flags;
  145.   mp3data_struct mp3data;
  146.  
  147.   out=lame_decode_ogg_fromfile(musicin,mpg123pcm[0],mpg123pcm[1],&mp3data);
  148.   /* out = -1:  error, probably EOF */
  149.   /* out = 0:   not possible with lame_decode_fromfile() */
  150.   /* out = number of output samples */
  151.  
  152.   if (out==-1) {
  153.     for ( j = 0; j < 1152; j++ ) {
  154.       mpg123pcm[0][j] = 0;
  155.       mpg123pcm[1][j] = 0;
  156.     }
  157.   }
  158.  
  159.   if (out==-1) return 0;
  160.  
  161.   gfp->brate=mp3data.bitrate;
  162.   if (gfp->num_channels != mp3data.stereo) {
  163.     ERRORF("Error: number of channels has changed in mp3 file - not supported. \n");
  164.   }
  165.   if (gfp->in_samplerate != mp3data.samplerate) {
  166.     ERRORF("Error: samplerate has changed in mp3 file - not supported. \n");
  167.   }
  168.  
  169.  
  170.   return out;
  171. #else
  172.   return -1; /* wanna read ogg without vorbis support? */
  173. #endif
  174. }
  175.  
  176.  
  177. int read_samples_mp3(lame_global_flags *gfp,FILE *musicin,short int mpg123pcm[2][1152],int stereo)
  178. {
  179. #if (defined  AMIGA_MPEGA || defined HAVEMPGLIB)
  180.   int j,out=0;
  181.   lame_internal_flags *gfc=gfp->internal_flags;
  182.   mp3data_struct mp3data;
  183.  
  184.   out=lame_decode_fromfile(musicin,mpg123pcm[0],mpg123pcm[1],&mp3data);
  185.   /* out = -1:  error, probably EOF */
  186.   /* out = 0:   not possible with lame_decode_fromfile() */
  187.   /* out = number of output samples */
  188.  
  189.   if (out==-1) {
  190.     for ( j = 0; j < 1152; j++ ) {
  191.       mpg123pcm[0][j] = 0;
  192.       mpg123pcm[1][j] = 0;
  193.     }
  194.   }
  195.  
  196.  
  197.   if (gfc->pinfo != NULL) {
  198.     int ch;
  199.     /* add a delay of framesize-DECDELAY, which will make the total delay
  200.      * exactly one frame, so we can sync MP3 output with WAV input */
  201.     for ( ch = 0; ch < stereo; ch++ ) {
  202.       for ( j = 0; j < gfp->framesize-DECDELAY; j++ )
  203.     gfc->pinfo->pcmdata2[ch][j] = gfc->pinfo->pcmdata2[ch][j+gfp->framesize];
  204.       for ( j = 0; j < gfp->framesize; j++ )
  205.     gfc->pinfo->pcmdata2[ch][j+gfp->framesize-DECDELAY] = mpg123pcm[ch][j];
  206.     }
  207.  
  208.   gfc->pinfo->frameNum123 = gfp->frameNum-1;
  209.   gfc->pinfo->frameNum = gfp->frameNum;
  210.   }
  211.  
  212.   if (out==-1) return 0;
  213.  
  214.   gfp->brate=mp3data.bitrate;
  215.   if (gfp->num_channels != mp3data.stereo) {
  216.     ERRORF("Error: number of channels has changed in mp3 file - not supported. \n");
  217.   }
  218.   if (gfp->in_samplerate != mp3data.samplerate) {
  219.     ERRORF("Error: samplerate has changed in mp3 file - not supported. \n");
  220.   }
  221.   return out;
  222.  
  223. #endif
  224. }
  225.  
  226.  
  227.  
  228.  
  229.  
  230. void WriteWav(FILE *f,long bytes,int srate,int ch){
  231.   /* quick and dirty */
  232.   fwrite("RIFF",1,4,f);               /*  0-3 */
  233.   Write32BitsLowHigh(f,bytes+44-8);
  234.   fwrite("WAVEfmt ",1,8,f);           /*  8-15 */
  235.   Write32BitsLowHigh(f,16);
  236.   Write16BitsLowHigh(f,1);
  237.   Write16BitsLowHigh(f,ch);
  238.   Write32BitsLowHigh(f,srate);
  239.   Write32BitsLowHigh(f,srate*ch*2);
  240.   Write16BitsLowHigh(f,4);
  241.   Write16BitsLowHigh(f,16);
  242.   fwrite("data",1,4,f);               /* 36-39 */
  243.   Write32BitsLowHigh(f,bytes);
  244. }
  245.  
  246. /* the simple lame decoder */
  247. /* After calling lame_init(), lame_init_params() and
  248.  * lame_init_infile(), call this routine to read the input MP3 file
  249.  * and output .wav data to the specified file pointer*/
  250. /* lame_decoder will ignore the first 528 samples, since these samples
  251.  * represent the mpglib delay (and are all 0).  skip = number of additional
  252.  * samples to skip, to (for example) compensate for the encoder delay */
  253. int lame_decoder(lame_global_flags *gfp,FILE *outf,int skip)
  254. {
  255.   short int Buffer[2][1152];
  256.   int iread;
  257.   long wavsize=2147483647L;  /* max for a signed long */
  258.  
  259.   if (gfp->input_format==sf_mp3) {
  260.     /* mp3 decoder has a 528 sample delay, plus user supplied "skip" */
  261.     skip+=528;
  262.     MSGF("input:    %s %.1fkHz MPEG%i %i channel LayerIII\n",
  263.       (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  264.       gfp->in_samplerate/1000.0,2-gfp->version,gfp->num_channels);
  265.  
  266.   }else{
  267.     /* other formats have no delay */
  268.     skip=0;
  269.     MSGF("input:    %s %.1fkHz %i channel\n",
  270.       (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  271.       gfp->in_samplerate/1000.0,gfp->num_channels);
  272.   }
  273.  
  274.   MSGF("output:   %s (wav format)\n",
  275.       (strcmp(gfp->outPath, "-")? gfp->outPath : "stdout"));
  276.   if (skip>0)
  277.     MSGF("skipping initial %i samples (encoder + decoder delay)\n",skip);
  278.   WriteWav(outf,wavsize,gfp->in_samplerate,gfp->num_channels);
  279.   wavsize=-skip;
  280.   do {
  281.     int i;
  282.     /* read in 'iread' samples */
  283.     iread=lame_readframe(gfp,Buffer);
  284.     wavsize += iread;
  285.     if (!gfp->silent)
  286.       decoder_progress(gfp);
  287.     for (i=0; i<iread; ++i) {
  288.       if (skip) {
  289.     --skip;
  290.       }else{
  291.     Write16BitsLowHigh(outf,Buffer[0][i]);
  292.     if (gfp->num_channels==2)
  293.       Write16BitsLowHigh(outf,Buffer[1][i]);
  294.       }
  295.     }
  296.   } while (iread);
  297.   if (wavsize<0) wavsize=0;
  298.   wavsize *= 2*gfp->num_channels;
  299.   decoder_progress_finish(gfp);
  300.   /* if outf is seekable, rewind and adjust length */
  301.   if (!fseek(outf,0,SEEK_SET))
  302.     WriteWav(outf,wavsize,gfp->in_samplerate,gfp->num_channels);
  303.   fclose(outf);
  304.  
  305.   return 0;
  306. }
  307.  
  308.  
  309. #endif  /* LAMESNDFILE or LIBSNDFILE */
  310.  
  311.  
  312.  
  313.  
  314. #ifdef LIBSNDFILE
  315. /*
  316. ** Copyright (C) 1999 Albert Faber
  317. **
  318.  * This library is free software; you can redistribute it and/or
  319.  * modify it under the terms of the GNU Library General Public
  320.  * License as published by the Free Software Foundation; either
  321.  * version 2 of the License, or (at your option) any later version.
  322.  *
  323.  * This library is distributed in the hope that it will be useful,
  324.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  325.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  326.  * Library General Public License for more details.
  327.  *
  328.  * You should have received a copy of the GNU Library General Public
  329.  * License along with this library; if not, write to the
  330.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  331.  * Boston, MA 02111-1307, USA.
  332.  */
  333.  
  334.  
  335. #include <stdio.h>
  336.  
  337.  
  338.  
  339.  
  340. void CloseSndFile(sound_file_format input,FILE *musicin)
  341. {
  342.   SNDFILE *gs_pSndFileIn=(SNDFILE*)musicin;
  343.   if (input==sf_mp3) {
  344. #ifndef AMIGA_MPEGA
  345.     if (fclose(musicin) != 0){
  346.       ERRORF("Could not close audio input file\n");
  347.       LAME_FATAL_EXIT();
  348.     }
  349. #endif
  350.   }else{
  351.     if (gs_pSndFileIn)
  352.     {
  353.         if (sf_close(gs_pSndFileIn) !=0)
  354.         {
  355.             ERRORF("Could not close sound file \n");
  356.             LAME_FATAL_EXIT();
  357.         }
  358.     }
  359.   }
  360. }
  361.  
  362.  
  363.  
  364. FILE * OpenSndFile(lame_global_flags *gfp)
  365. {
  366.   lame_internal_flags *gfc=gfp->internal_flags;
  367.   const char* lpszFileName = gfp->inPath;
  368.   FILE * musicin;
  369.   SNDFILE *gs_pSndFileIn;
  370.   SF_INFO gs_wfInfo;
  371.  
  372.   gfc->input_bitrate=0;
  373.   if (gfp->input_format==sf_mp3) {
  374.     mp3data_struct mp3data;
  375. #ifdef AMIGA_MPEGA
  376.     if (-1==lame_decode_initfile(lpszFileName,&mp3data)) {
  377.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  378.       LAME_ERROR_EXIT();
  379.     }
  380. #endif
  381. #ifdef HAVEMPGLIB
  382.     if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  383.       ERRORF("Could not find \"%s\".\n", lpszFileName);
  384.       LAME_ERROR_EXIT();
  385.     }
  386.     if (-1==lame_decode_initfile(musicin,&mp3data)) {
  387.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  388.       LAME_ERROR_EXIT();
  389.     }
  390. #endif
  391.  
  392.     gfp->num_channels=mp3data.stereo;
  393.     gfp->in_samplerate=mp3data.samplerate;
  394.     gfc->input_bitrate=mp3data.bitrate;
  395.     gfp->num_samples=mp3data.nsamp;
  396.   }else if (gfp->input_format==sf_ogg) {
  397. #ifdef HAVEVORBIS
  398.     if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
  399.       ERRORF("Could not find \"%s\".\n", lpszFileName);
  400.       LAME_ERROR_EXIT();
  401.     }
  402.     if (-1==lame_decode_ogg_initfile(musicin,&mp3data)) {
  403.       ERRORF("Error reading headers in mp3 input file %s.\n", lpszFileName);
  404.       LAME_ERROR_EXIT();
  405.     }
  406.     gfp->num_channels=0;
  407.     gfp->in_samplerate=0;
  408.     gfc->input_bitrate=0;
  409.     gfp->num_samples=0;
  410. #else
  411.     ERRORF("LAME not compiled with libvorbis support.\n");
  412.     LAME_ERROR_EXIT();
  413. #endif
  414.  
  415.  
  416.   } else {
  417.  
  418.     /* Try to open the sound file */
  419.     /* set some defaults incase input is raw PCM */
  420.     gs_wfInfo.seekable=(gfp->input_format!=sf_raw);  /* if user specified -r, set to not seekable */
  421.     gs_wfInfo.samplerate=gfp->in_samplerate;
  422.     gs_wfInfo.pcmbitwidth=16;
  423.     gs_wfInfo.channels=gfp->num_channels;
  424.     if (DetermineByteOrder()==order_littleEndian) {
  425.       if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_BE;
  426.       else gs_wfInfo.format=SF_FORMAT_RAW_LE;
  427.     } else {
  428.       if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_LE;
  429.       else gs_wfInfo.format=SF_FORMAT_RAW_BE;
  430.     }
  431.  
  432.     gs_pSndFileIn=sf_open_read(lpszFileName,&gs_wfInfo);
  433.     musicin = (SNDFILE *) gs_pSndFileIn;
  434.  
  435.         /* Check result */
  436.     if (gs_pSndFileIn==NULL)
  437.     {
  438.             sf_perror(gs_pSndFileIn);
  439.         ERRORF("Could not open sound file \"%s\".\n", lpszFileName);
  440.         LAME_ERROR_EXIT();
  441.     }
  442.  
  443.     if ((gs_wfInfo.format==SF_FORMAT_RAW_LE) ||
  444.     (gs_wfInfo.format==SF_FORMAT_RAW_BE))
  445.       gfp->input_format=sf_raw;
  446.  
  447. #ifdef _DEBUG_SND_FILE
  448.     DEBUGF("\n\nSF_INFO structure\n");
  449.     DEBUGF("samplerate        :%d\n",gs_wfInfo.samplerate);
  450.     DEBUGF("samples           :%d\n",gs_wfInfo.samples);
  451.     DEBUGF("channels          :%d\n",gs_wfInfo.channels);
  452.     DEBUGF("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
  453.     DEBUGF("format            :");
  454.  
  455.     /* new formats from sbellon@sbellon.de  1/2000 */
  456.         if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_WAV)
  457.       DEBUGF("Microsoft WAV format (big endian). ");
  458.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AIFF)
  459.       DEBUGF("Apple/SGI AIFF format (little endian). ");
  460.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AU)
  461.       DEBUGF("Sun/NeXT AU format (big endian). ");
  462.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AULE)
  463.       DEBUGF("DEC AU format (little endian). ");
  464.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_RAW)
  465.       DEBUGF("RAW PCM data. ");
  466.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_PAF)
  467.       DEBUGF("Ensoniq PARIS file format. ");
  468.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_SVX)
  469.       DEBUGF("Amiga IFF / SVX8 / SV16 format. ");
  470.     if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_NIST)
  471.       DEBUGF("Sphere NIST format. ");
  472.  
  473.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM)
  474.       DEBUGF("PCM data in 8, 16, 24 or 32 bits.");
  475.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_FLOAT)
  476.       DEBUGF("32 bit Intel x86 floats.");
  477.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ULAW)
  478.       DEBUGF("U-Law encoded.");
  479.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ALAW)
  480.       DEBUGF("A-Law encoded.");
  481.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_IMA_ADPCM)
  482.       DEBUGF("IMA ADPCM.");
  483.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_MS_ADPCM)
  484.       DEBUGF("Microsoft ADPCM.");
  485.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_BE)
  486.       DEBUGF("Big endian PCM data.");
  487.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_LE)
  488.       DEBUGF("Little endian PCM data.");
  489.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_S8)
  490.       DEBUGF("Signed 8 bit PCM.");
  491.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_U8)
  492.       DEBUGF("Unsigned 8 bit PCM.");
  493.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_FIB)
  494.       DEBUGF("SVX Fibonacci Delta encoding.");
  495.     if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_EXP)
  496.       DEBUGF("SVX Exponential Delta encoding.");
  497.  
  498.  
  499.  
  500.  
  501.     DEBUGF("\n");
  502.     DEBUGF("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
  503.     DEBUGF("sections          :%d\n",gs_wfInfo.sections);
  504.     DEBUGF("seekable          :\n",gs_wfInfo.seekable);
  505. #endif
  506.  
  507.     gfp->num_samples = gs_wfInfo.samples;
  508.     gfp->num_channels = gs_wfInfo.channels;
  509.     gfp->in_samplerate = gs_wfInfo.samplerate;
  510.     gfc->pcmbitwidth=gs_wfInfo.pcmbitwidth;
  511.   }
  512.  
  513.   if (gfp->num_samples==MAX_U_32_NUM) {
  514.     struct stat sb;
  515. #ifdef __riscos__
  516.     _kernel_swi_regs reg;
  517. #endif
  518.  
  519.     /* try to figure out num_samples */
  520. #ifndef __riscos__
  521.     if (0==stat(lpszFileName,&sb)) {
  522. #else /* __riscos__ */
  523.     reg.r[0]=17;
  524.     reg.r[1]=(int) lpszFileName;
  525.     _kernel_swi(OS_File,®,®);
  526.     if (reg.r[0] == 1) {
  527.       sb.st_size=reg.r[4];
  528. #endif /* __riscos__ */
  529.  
  530.       /* try file size, assume 2 bytes per sample */
  531.       if (gfp->input_format == sf_mp3) {
  532.     FLOAT totalseconds = (sb.st_size*8.0/(1000.0*gfc->input_bitrate));
  533.     gfp->num_samples= totalseconds*gfp->in_samplerate;
  534.       }else{
  535.     gfp->num_samples = sb.st_size/(2*gfp->num_channels);
  536.       }
  537.     }
  538.   }
  539.  
  540.  
  541.   return musicin;
  542. }
  543.  
  544.  
  545. /************************************************************************
  546. *
  547. * read_samples()
  548. *
  549. * PURPOSE:  reads the PCM samples from a file to the buffer
  550. *
  551. *  SEMANTICS:
  552. * Reads #samples_read# number of shorts from #musicin# filepointer
  553. * into #sample_buffer[]#.  Returns the number of samples read.
  554. *
  555. ************************************************************************/
  556.  
  557. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304],int frame_size,int samples_to_read)
  558. {
  559.     int         samples_read;
  560.     int            rcode;
  561.     lame_internal_flags *gfc=gfp->internal_flags;
  562.     SNDFILE * gs_pSndFileIn;
  563.     gs_pSndFileIn = (SNDFILE *)gfp->musicin;
  564.  
  565.     samples_read=sf_read_short(gs_pSndFileIn,sample_buffer,samples_to_read);
  566.     rcode = samples_read;
  567.  
  568.     if (8==gfc->pcmbitwidth)
  569.       for (; samples_read > 0; sample_buffer[--samples_read] *= 256);
  570.  
  571.     return(rcode);
  572. }
  573.  
  574.  
  575. #endif /* ifdef LIBSNDFILE */
  576. #ifdef LAMESNDFILE
  577.  
  578. /************************************************************************
  579.  ************************************************************************
  580.  ************************************************************************
  581.  ************************************************************************
  582.  ************************************************************************
  583.  ************************************************************************
  584.  *
  585.  * OLD ISO/LAME routines follow.  Used if you dont have LIBSNDFILE
  586.  * or for stdin/stdout support
  587.  *
  588.  ************************************************************************
  589.  ************************************************************************
  590.  ************************************************************************
  591.  ************************************************************************
  592.  ************************************************************************
  593.  ************************************************************************/
  594.  
  595. /* Replacement for forward fseek(,,SEEK_CUR), because fseek() fails on pipes */
  596. int fskip(FILE *sf,long num_bytes,int dummy)
  597. {
  598.   char data[1024];
  599.   int nskip = 0;
  600.   while (num_bytes > 0) {
  601.     nskip = (num_bytes>1024) ? 1024 : num_bytes;
  602.     num_bytes -= fread(data,(size_t)1,(size_t)nskip,sf);
  603.   }
  604.   /* return 0 if last read was successful */
  605.   return num_bytes;
  606. }
  607.  
  608.  
  609. /************************************************************************
  610. *
  611. * read_samples()
  612. *
  613. * PURPOSE:  reads the PCM samples from a file to the buffer
  614. *
  615. *  SEMANTICS:
  616. * Reads #samples_read# number of shorts from #musicin# filepointer
  617. * into #sample_buffer[]#.  Returns the number of samples read.
  618. *
  619. ************************************************************************/
  620.  
  621. int read_samples_pcm(lame_global_flags *gfp,short sample_buffer[2304], int frame_size,int samples_to_read)
  622. {
  623.     lame_internal_flags *gfc=gfp->internal_flags;
  624.     int samples_read;
  625.     int iswav=(gfp->input_format==sf_wave);
  626.  
  627.     if (16==gfc->pcmbitwidth) {
  628.       samples_read = fread(sample_buffer, 2, (unsigned int)samples_to_read, gfp->musicin);
  629.     }else if (8==gfc->pcmbitwidth) {
  630.       signed char temp[2304];
  631.       int i;
  632.       samples_read = fread(temp, 1, (unsigned int)samples_to_read, gfp->musicin);
  633.       for (i=0 ; i<samples_read; ++i)
  634.     sample_buffer[i]=(short int)temp[i]*256;
  635.     }else{
  636.       ERRORF("Only 8 and 16 bit input files supported \n");
  637.       LAME_ERROR_EXIT();
  638.     }
  639.     if (ferror(gfp->musicin)) {
  640.       ERRORF("Error reading input file\n");
  641.       LAME_ERROR_EXIT();
  642.     }
  643.  
  644.  
  645.     /*
  646.        Samples are big-endian. If this is a little-endian machine
  647.        we must swap
  648.      */
  649.     if ( NativeByteOrder == order_unknown )
  650.       {
  651.     NativeByteOrder = DetermineByteOrder();
  652.     if ( NativeByteOrder == order_unknown )
  653.       {
  654.         ERRORF("byte order not determined\n" );
  655.         LAME_ERROR_EXIT();
  656.       }
  657.       }
  658.     /* intel=littleEndian */
  659.     if (!iswav && ( NativeByteOrder == order_littleEndian ))
  660.       SwapBytesInWords( sample_buffer, samples_read );
  661.  
  662.     if (iswav && ( NativeByteOrder == order_bigEndian ))
  663.       SwapBytesInWords( sample_buffer, samples_read );
  664.  
  665.     if (gfp->swapbytes==TRUE)
  666.       SwapBytesInWords( sample_buffer, samples_read );
  667.  
  668.  
  669.     return samples_read;
  670. }
  671.  
  672.  
  673.  
  674. /* AIFF Definitions */
  675.  
  676. #define IFF_ID_FORM 0x464f524d /* "FORM" */
  677. #define IFF_ID_AIFF 0x41494646 /* "AIFF" */
  678. #define IFF_ID_COMM 0x434f4d4d /* "COMM" */
  679. #define IFF_ID_SSND 0x53534e44 /* "SSND" */
  680. #define IFF_ID_MPEG 0x4d504547 /* "MPEG" */
  681.  
  682.  
  683. #define WAV_ID_RIFF 0x52494646 /* "RIFF" */
  684. #define WAV_ID_WAVE 0x57415645 /* "WAVE" */
  685. #define WAV_ID_FMT  0x666d7420 /* "fmt " */
  686. #define WAV_ID_DATA 0x64617461 /* "data" */
  687.  
  688. typedef struct fmt_chunk_data_struct {
  689.     short    format_tag;             /* Format category */
  690.     u_short channels;             /* Number of channels */
  691.     u_long    samples_per_sec;     /* Sampling rate */
  692.     u_long    avg_bytes_per_sec;     /* For buffer estimation */
  693.     u_short block_align;         /* Data block size */
  694.     u_short bits_per_sample;     /* for PCM data, anyway... */
  695. } fmt_chunk_data;
  696.  
  697.  
  698.  
  699.  
  700.  
  701.  
  702.  
  703. /*****************************************************************************
  704.  *
  705.  *    Read Microsoft Wave headers
  706.  *
  707.  *    By the time we get here the first 32-bits of the file have already been
  708.  *    read, and we're pretty sure that we're looking at a WAV file.
  709.  *
  710.  *****************************************************************************/
  711.  
  712. static int
  713. parse_wave_header(lame_global_flags *gfp,FILE *sf)
  714. {
  715.     lame_internal_flags *gfc=gfp->internal_flags;
  716.     fmt_chunk_data wave_info;
  717.     int is_wav = 0;
  718.     long data_length = 0, file_length, subSize = 0;
  719.     int loop_sanity = 0;
  720.  
  721.     memset(&wave_info, 0, sizeof(wave_info));
  722.  
  723.     file_length = Read32BitsHighLow(sf);
  724.  
  725.     if (Read32BitsHighLow(sf) != WAV_ID_WAVE)
  726.         return 0;
  727.  
  728.     for (loop_sanity = 0; loop_sanity < 20; ++loop_sanity) {
  729.         u_int type = Read32BitsHighLow(sf);
  730.  
  731.         if (type == WAV_ID_FMT) {
  732.             subSize = Read32BitsLowHigh(sf);
  733.             if (subSize < 16) {
  734.               /*DEBUGF(
  735.                 "'fmt' chunk too short (only %ld bytes)!", subSize);  */
  736.                 return 0;
  737.             }
  738.  
  739.             wave_info.format_tag        = Read16BitsLowHigh(sf);
  740.             subSize -= 2;
  741.             wave_info.channels            = Read16BitsLowHigh(sf);
  742.             subSize -= 2;
  743.             wave_info.samples_per_sec    = Read32BitsLowHigh(sf);
  744.             subSize -= 4;
  745.             wave_info.avg_bytes_per_sec = Read32BitsLowHigh(sf);
  746.             subSize -= 4;
  747.             wave_info.block_align        = Read16BitsLowHigh(sf);
  748.             subSize -= 2;
  749.             wave_info.bits_per_sample    = Read16BitsLowHigh(sf);
  750.             subSize -= 2;
  751.  
  752.             /* DEBUGF("   skipping %d bytes\n", subSize); */
  753.  
  754.             if (subSize > 0) {
  755.                 if (fskip(sf, (long)subSize, SEEK_CUR) != 0 )
  756.                     return 0;
  757.             };
  758.  
  759.         } else if (type == WAV_ID_DATA) {
  760.             subSize = Read32BitsLowHigh(sf);
  761.             data_length = subSize;
  762.             is_wav = 1;
  763.             /* We've found the audio data.    Read no further! */
  764.             break;
  765.  
  766.         } else {
  767.             subSize = Read32BitsLowHigh(sf);
  768.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 ) return 0;
  769.         }
  770.     }
  771.  
  772.     if (is_wav) {
  773.         /* make sure the header is sane */
  774.         gfp->num_channels  = wave_info.channels;
  775.         gfp->in_samplerate = wave_info.samples_per_sec;
  776.         gfc->pcmbitwidth = wave_info.bits_per_sample;
  777.         gfp->num_samples   = data_length / (wave_info.channels * wave_info.bits_per_sample / 8);
  778.     }
  779.     return is_wav;
  780. }
  781.  
  782.  
  783.  
  784. /************************************************************************
  785. *
  786. * aiff_check
  787. *
  788. * PURPOSE:    Checks AIFF header information to make sure it is valid.
  789. *            Exits if not.
  790. *
  791. ************************************************************************/
  792.  
  793. static void
  794. aiff_check2(const char *file_name, IFF_AIFF *pcm_aiff_data)
  795. {
  796.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  797.        ERRORF("Sound data is not PCM in \"%s\".\n", file_name);
  798.        LAME_ERROR_EXIT();
  799.     }
  800.  
  801.     if (pcm_aiff_data->sampleSize != sizeof(short) * BITS_IN_A_BYTE) {
  802.         ERRORF("Sound data is not %d bits in \"%s\".\n",
  803.                 (unsigned int) sizeof(short) * BITS_IN_A_BYTE, file_name);
  804.         LAME_ERROR_EXIT();
  805.     }
  806.  
  807.     if (pcm_aiff_data->numChannels != 1 &&
  808.         pcm_aiff_data->numChannels != 2) {
  809.        ERRORF("Sound data is not mono or stereo in \"%s\".\n",
  810.                file_name);
  811.        LAME_ERROR_EXIT();
  812.     }
  813.  
  814.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  815.        ERRORF("Block size is not %d bytes in \"%s\".\n",
  816.                0, file_name);
  817.        LAME_ERROR_EXIT();
  818.     }
  819.  
  820.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  821.        ERRORF("Block offset is not %d bytes in \"%s\".\n",
  822.                0, file_name);
  823.        LAME_ERROR_EXIT();
  824.     }
  825. }
  826.  
  827. /*****************************************************************************
  828.  *
  829.  *    Read Audio Interchange File Format (AIFF) headers.
  830.  *
  831.  *    By the time we get here the first 32-bits of the file have already been
  832.  *    read, and we're pretty sure that we're looking at an AIFF file.
  833.  *
  834.  *****************************************************************************/
  835.  
  836. static int
  837. parse_aiff_header(lame_global_flags *gfp,FILE *sf)
  838. {
  839.     lame_internal_flags *gfc=gfp->internal_flags;
  840.     int is_aiff = 0;
  841.     long chunkSize = 0, subSize = 0;
  842.     IFF_AIFF aiff_info;
  843.  
  844.     memset(&aiff_info, 0, sizeof(aiff_info));
  845.     chunkSize = Read32BitsHighLow(sf);
  846.  
  847.     if ( Read32BitsHighLow(sf) != IFF_ID_AIFF )
  848.         return 0;
  849.  
  850.     while ( chunkSize > 0 )
  851.     {
  852.         u_int type = 0;
  853.         chunkSize -= 4;
  854.  
  855.         type = Read32BitsHighLow(sf);
  856.  
  857.         /* DEBUGF(
  858.             "found chunk type %08x '%4.4s'\n", type, (char*)&type); */
  859.  
  860.         /* don't use a switch here to make it easier to use 'break' for SSND */
  861.         if (type == IFF_ID_COMM) {
  862.             subSize = Read32BitsHighLow(sf);
  863.             chunkSize -= subSize;
  864.  
  865.             aiff_info.numChannels      = Read16BitsHighLow(sf);
  866.             subSize -= 2;
  867.             aiff_info.numSampleFrames = Read32BitsHighLow(sf);
  868.             subSize -= 4;
  869.             aiff_info.sampleSize      = Read16BitsHighLow(sf);
  870.             subSize -= 2;
  871.             aiff_info.sampleRate      = ReadIeeeExtendedHighLow(sf);
  872.             subSize -= 10;
  873.  
  874.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 )
  875.                 return 0;
  876.  
  877.         } else if (type == IFF_ID_SSND) {
  878.             subSize = Read32BitsHighLow(sf);
  879.             chunkSize -= subSize;
  880.  
  881.             aiff_info.blkAlgn.offset    = Read32BitsHighLow(sf);
  882.             subSize -= 4;
  883.             aiff_info.blkAlgn.blockSize = Read32BitsHighLow(sf);
  884.             subSize -= 4;
  885.  
  886.             if (fskip(sf, (long) aiff_info.blkAlgn.offset, SEEK_CUR) != 0 )
  887.                 return 0;
  888.  
  889.             aiff_info.sampleType = IFF_ID_SSND;
  890.             is_aiff = 1;
  891.  
  892.             /* We've found the audio data.    Read no further! */
  893.             break;
  894.  
  895.         } else {
  896.             subSize = Read32BitsHighLow(sf);
  897.             chunkSize -= subSize;
  898.  
  899.             if (fskip(sf, (long) subSize, SEEK_CUR) != 0 )
  900.                 return 0;
  901.         }
  902.     }
  903.  
  904.     /* DEBUGF("Parsed AIFF %d\n", is_aiff); */
  905.     if (is_aiff) {
  906.         /* make sure the header is sane */
  907.         aiff_check2("name", &aiff_info);
  908.         gfp->num_channels  = aiff_info.numChannels;
  909.         gfp->in_samplerate = aiff_info.sampleRate;
  910.         gfc->pcmbitwidth =   aiff_info.sampleSize;
  911.         gfp->num_samples   = aiff_info.numSampleFrames;
  912.     }
  913.     return is_aiff;
  914. }
  915.  
  916.  
  917.  
  918. /************************************************************************
  919. *
  920. * parse_file_header
  921. *
  922. * PURPOSE: Read the header from a bytestream.  Try to determine whether
  923. *           it's a WAV file or AIFF without rewinding, since rewind
  924. *           doesn't work on pipes and there's a good chance we're reading
  925. *           from stdin (otherwise we'd probably be using libsndfile).
  926. *
  927. * When this function returns, the file offset will be positioned at the
  928. * beginning of the sound data.
  929. *
  930. ************************************************************************/
  931.  
  932. void parse_file_header(lame_global_flags *gfp,FILE *sf)
  933. {
  934.   lame_internal_flags *gfc=gfp->internal_flags;
  935.  
  936.     u_int type = 0;
  937.     type = Read32BitsHighLow(sf);
  938.     /*
  939.     DEBUGF(
  940.         "First word of input stream: %08x '%4.4s'\n", type, (char*) &type); 
  941.     */
  942.     gfc->count_samples_carefully=0;
  943.     gfp->input_format = sf_raw;
  944.  
  945.     if (type == WAV_ID_RIFF) {
  946.         /* It's probably a WAV file */
  947.         if (parse_wave_header(gfp,sf)) {
  948.             gfp->input_format = sf_wave;
  949.             gfc->count_samples_carefully=1;
  950.         }
  951.  
  952.     } else if (type == IFF_ID_FORM) {
  953.         /* It's probably an AIFF file */
  954.         if (parse_aiff_header(gfp,sf)) {
  955.             gfp->input_format = sf_aiff;
  956.             gfc->count_samples_carefully=1;
  957.         }
  958.     }
  959.     if (gfp->input_format==sf_raw) {
  960.       /*
  961.       ** Assume it's raw PCM.     Since the audio data is assumed to begin
  962.       ** at byte zero, this will unfortunately require seeking.
  963.       */
  964.       if (fseek(sf, 0L, SEEK_SET) != 0) {
  965.         /* ignore errors */
  966.       }
  967.       gfp->input_format = sf_raw;
  968.     }
  969. }
  970.  
  971.  
  972.  
  973. void CloseSndFile(sound_file_format input,FILE * musicin)
  974. {
  975.   if (fclose(musicin) != 0){
  976.     ERRORF("Could not close audio input file\n");
  977.     LAME_FATAL_EXIT();
  978.   }
  979. }
  980.  
  981.  
  982.  
  983.  
  984.  
  985. FILE * OpenSndFile(lame_global_flags *gfp)
  986. {
  987.   lame_internal_flags *gfc=gfp->internal_flags;
  988.   const char* inPath = gfp->inPath;
  989.   FILE * musicin;
  990.   struct stat sb;
  991.  
  992.   /* set the defaults from info incase we cannot determine them from file */
  993.   gfp->num_samples=MAX_U_32_NUM;
  994.   gfc->input_bitrate=0;
  995.  
  996.  
  997.   if (!strcmp(inPath, "-")) {
  998.     /* Read from standard input. */
  999. #ifdef __EMX__
  1000.     _fsetmode(stdin,"b");
  1001. #elif (defined  __BORLANDC__)
  1002.     setmode(_fileno(stdin), O_BINARY);
  1003. #elif (defined  __CYGWIN__)
  1004.     setmode(fileno(stdin), _O_BINARY);
  1005. #elif (defined _WIN32)
  1006.     _setmode(_fileno(stdin), _O_BINARY);
  1007. #endif
  1008.     musicin = stdin;
  1009.   } else {
  1010.     if ((musicin = fopen(inPath, "rb")) == NULL) {
  1011.       ERRORF("Could not find \"%s\".\n", inPath);
  1012.       LAME_ERROR_EXIT();
  1013.     }
  1014.   }
  1015.  
  1016.   if (gfp->input_format==sf_mp3) {
  1017.     mp3data_struct mp3data;
  1018. #ifdef AMIGA_MPEGA
  1019.     if (-1==lame_decode_initfile(inPath,&mp3data)) {
  1020.       ERRORF("Error reading headers in mp3 input file %s.\n", inPath);
  1021.       LAME_ERROR_EXIT();
  1022.     }
  1023. #endif
  1024. #ifdef HAVEMPGLIB
  1025.     if (-1==lame_decode_initfile(musicin,&mp3data)) {
  1026.       ERRORF("Error reading headers in mp3 input file %s.\n", inPath);
  1027.       LAME_ERROR_EXIT();
  1028.     }
  1029. #endif
  1030.     gfp->num_channels=mp3data.stereo;
  1031.     gfp->in_samplerate=mp3data.samplerate;
  1032.     gfc->input_bitrate=mp3data.bitrate;
  1033.     gfp->num_samples=mp3data.nsamp;
  1034.   }else if (gfp->input_format==sf_ogg) {
  1035. #ifdef HAVEVORBIS
  1036.     mp3data_struct mp3data;
  1037.     if (-1==lame_decode_ogg_initfile(musicin,&mp3data)) {
  1038.       ERRORF("Error reading headers in ogg input file %s.\n", inPath);
  1039.       LAME_ERROR_EXIT();
  1040.     }
  1041.     gfp->num_channels=mp3data.stereo;
  1042.     gfp->in_samplerate=mp3data.samplerate;
  1043.     gfc->input_bitrate=mp3data.bitrate;
  1044.     gfp->num_samples=mp3data.nsamp;
  1045. #else
  1046.     ERRORF("LAME not compiled with libvorbis support.\n");
  1047.     LAME_ERROR_EXIT();
  1048. #endif
  1049.  }else{
  1050.    if (gfp->input_format != sf_raw) {
  1051.      parse_file_header(gfp,musicin);
  1052.    }
  1053.  
  1054.    if (gfp->input_format==sf_raw) {
  1055.      /* assume raw PCM */
  1056.      MSGF("Assuming raw pcm input file");
  1057.      if (gfp->swapbytes==TRUE)
  1058.        MSGF(" : Forcing byte-swapping\n");
  1059.      else
  1060.        MSGF("\n");
  1061.    }
  1062.  }
  1063.  
  1064.   if (gfp->num_samples==MAX_U_32_NUM && musicin != stdin) {
  1065. #ifdef __riscos__
  1066.     _kernel_swi_regs reg;
  1067. #endif
  1068.  
  1069.     /* try to figure out num_samples */
  1070. #ifndef __riscos__
  1071.     if (0==stat(inPath,&sb)) {
  1072. #else
  1073.     reg.r[0]=17;
  1074.     reg.r[1]=(int) inPath;
  1075.     _kernel_swi(OS_File,®,®);
  1076.     if (reg.r[0] == 1) {
  1077.       sb.st_size=reg.r[4];
  1078. #endif
  1079.  
  1080.       /* try file size, assume 2 bytes per sample */
  1081.       if (gfp->input_format == sf_mp3) {
  1082.     if (gfc->input_bitrate>0) {
  1083.       FLOAT totalseconds = (sb.st_size*8.0/(1000.0*gfc->input_bitrate));
  1084.       gfp->num_samples= totalseconds*gfp->in_samplerate;
  1085.     }
  1086.       }else{
  1087.     gfp->num_samples = sb.st_size/(2*gfp->num_channels);
  1088.       }
  1089.     }
  1090.   }
  1091.   return musicin;
  1092. }
  1093. #endif  /* LAMESNDFILE */
  1094.  
  1095.  
  1096.